import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { reqGetUserInfoAsync, reqLoginAsync, reqLogoutAsync } from '@/api/user'
import {allRoutesAsync, anyRoute, constantRoutes} from '@/router/routes'
import {cloneDeep} from "lodash/lang";

// 用来筛选登录用户 可以访问的 对应路由信息表
function filterMenuPermission(allRoutesAsync, routes) {
  return allRoutesAsync.filter(item => {
    // 判断是否包含 不包含就 过滤
    if (!routes.includes(item.name)) return false
    if (item.children && item.children.length >= 0) {
      item.children = filterMenuPermission(item.children, routes)
    }
    return true
  })
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '', // 用户名称
    avatar: '', // 用户头像
    buttons: [], // 用户的按钮权限数据
    roles: [], // 用户的角色信息
    routes: [], // 用户的拥有的菜单权限的名称
    menuRouter: [] // 用户可以看到的菜单
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSION: (state, payload) => {
    state.buttons = payload.buttons
    state.roles = payload.roles
    state.routes = payload.routes
  },
  SET_MENUROUTER: (state, menuRouter) => {
    state.menuRouter = menuRouter
  }
}

const actions = {
  // 登录功能
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    try {
      const result = await reqLoginAsync({ username: username.trim(), password: password })
      // 获取用户信息
      const { data } = result
      // 保存token
      commit('SET_TOKEN', data.token)
      // 把token放在本地缓存
      setToken(data.token)
    } catch (e) {
      return Promise.reject('登录失败')
    }
  },

  // 获取用户信息功能
  async getInfo({ commit }) {
    try {
      const { data } = await reqGetUserInfoAsync()
      if (!data) return Promise.reject('验证失败，请重新登录。')
      // 提取用户名称和头像
      const { name, avatar, buttons, roles, routes } = data
      // 保存用户名称
      commit('SET_NAME', name)
      // 保存用户头像
      commit('SET_AVATAR', avatar)
      // 保存用户权限
      commit('SET_PERMISSION', { buttons, roles, routes })
      // 用来筛选登录用户 可以访问的 对应路由信息表
      const filterRoutes = filterMenuPermission(cloneDeep(allRoutesAsync), routes)
      // 保用用户可以看到的左侧菜单
      commit('SET_MENUROUTER', [...constantRoutes, ...filterRoutes])
      // 动态添加路由
      router.addRoutes([...filterRoutes])
    } catch (e) {
      return Promise.reject('获取用户信息失败')
    }
  },
  // user logout
  async logout({ commit }) {
    try {
      // 退出登录
      await reqLogoutAsync()
      // 清除本地存储的token
      removeToken()
      // 重置路由表
      resetRouter()
      // 清除所有用户信息
      commit('RESET_STATE')
    } catch (e) {
      return Promise.reject('退出登录失败')
    }
  },

  // 清除本地存储的token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

